<?php

namespace System\Core;

class Model
{
    protected $db;
    protected $table;

    public function __construct()
    {
        $this->db = Db::getInstance();
    }

    public function all()
    {
        $sql = "SELECT * FROM {$this->table}";
        return $this->db->query($sql)->fetchAll();
    }

    public function find($id, $name = 'id')
    {
        $sql = "SELECT * FROM {$this->table} WHERE $name = ?";
        return $this->db->query($sql, [$id])->fetch();
    }

    public function create($data)
    {
        $keys = implode(', ', array_keys($data));
        $values = implode(', ', array_fill(0, count($data), '?'));
        $sql = "INSERT INTO {$this->table} ($keys) VALUES ($values)";
        return $this->db->query($sql, array_values($data));
    }

    public function update($data, $id)
    {
        $tj = '';
        foreach ($data as $key => $value) {
            $tj .= "$key = ?, ";
        }
        $tj = rtrim($tj, ', ');
        $idName = array_keys($id)[0];
        $sql = "UPDATE {$this->table} SET $tj WHERE $idName = ?";
        $da = array_merge(array_values($data), array_values($id));
        // print_r($da);
        return $this->db->query($sql, $da);
    }

    public function delete($id, $idName = 'id'){
        $sql = "DELETE FROM {$this->table} WHERE $idName = ?";
        return $this->db->query($sql, [$id]);
    }
}
